<template>
  <view class="container">
    <view class="form-item">
      <text>金额（元）</text>
      <input v-model="form.amount" type="number" placeholder="请输入金额">
    </view>

    <view class="form-item">
      <text>支付人</text>
      <picker @change="selectPayer" :range="members" range-key="name">
        <view>{{ form.payerName || '请选择支付人' }}</view>
      </picker>
    </view>

    <view class="form-item">
      <text>参与分摊成员</text>
      <checkbox-group @change="selectParticipants">
        <label v-for="member in members" :key="member.id">
          <checkbox :value="String(member.id)" :checked="form.participantIds.includes(member.id)" />
          <text>{{ member.name }}</text>
        </label>
      </checkbox-group>
    </view>

    <button @click="submit" type="primary">提交</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      members: [ // 从后端获取或写死
        { id: 1, name: '父亲' },
        { id: 2, name: '大哥' },
        { id: 3, name: '二哥' }
      ],
      form: {
        amount: '',
        payerId: null,
        payerName: '',
		ledgerId:1,
        participantIds: []
      }
    }
  },
  methods: {
    selectPayer(e) {
      const index = e.detail.value;
      this.form.payerId = this.members[index].id;
      this.form.payerName = this.members[index].name;
    },
    selectParticipants(e) {
      this.form.participantIds = e.detail.value;
    },
    async submit() {
      if (!this.validateForm()) return;

      const res = await uni.request({
        url: 'http://localhost:8080/api/expense',
        method: 'POST',
        data: {
			ledgerId:1,
          amount: this.form.amount,
          payerId: this.form.payerId,
          participantIds: this.form.participantIds.join(',')
        }
      });

      if (res.statusCode === 200) {
        uni.showToast({ title: '添加成功' });
        setTimeout(() => uni.navigateBack(), 1500);
      }
    },
    validateForm() {
      if (!this.form.amount) {
        uni.showToast({ title: '请输入金额', icon: 'none' });
        return false;
      }
      if (!this.form.payerId) {
        uni.showToast({ title: '请选择支付人', icon: 'none' });
        return false;
      }
      if (this.form.participantIds.length === 0) {
        uni.showToast({ title: '请选择分摊成员', icon: 'none' });
        return false;
      }
      return true;
    }
  }
}
</script>

<style>
.form-item {
  margin-bottom: 30rpx;
}
.form-item text {
  display: block;
  margin-bottom: 10rpx;
  font-weight: bold;
}
</style>